<script setup lang='ts'>
import type { VxeGridProps } from 'vxe-table'

import { useOpen } from '@/pages/home/component/use-open'
import { Search } from '@element-plus/icons-vue'
import { useGetManAgreementMetaInfo, useGetManExportAgreementInfo } from '@fl/api/man-api'
import { singleFileJsonObj } from '@fl/utils/fn'
import { ElButton, ElCard } from 'element-plus'
import { cloneDeep } from 'lodash-es'

const { openNewWindow } = useOpen()
const { back, push } = useRouter()
const { query } = useRoute()

const tableRef = ref(null)

const id = computed(() => {
    return query.id
})
const { data, isLoading } = useGetManAgreementMetaInfo(id)

const { isPending, mutate } = useGetManExportAgreementInfo()

const agreementTypeEunm = {
    1: '战略协议',
    2: '项目合同',
}

const isProjectContract = computed(() => agreementTypeEunm?.[data.value?.agreementType] === '项目合同')

const gridOptions = computed<VxeGridProps>(() => ({
    columns: [
        { field: 'productCode', title: '产品编码', width: 200 },
        { field: 'productName', title: '产品名称' },
        { field: 'skuName', title: '商品名称' },
        { field: 'brand', title: '品牌' },
        { field: 'model', title: '型号' },
        { field: 'unit', title: '单位' },
        { field: 'oldPrice', formatter: formatPrice, title: '协议价格', visible: isProjectContract.value, width: 100 },
        { field: 'sellingPrice', formatter: formatPrice, title: '价格(不含税)' },
        { field: 'agreementPrice', formatter: formatPrice, title: '价格(含税)' },
        { field: 'count', title: '数量', visible: isProjectContract.value },
        { slots: { default: 'operate' }, title: '操作' },
    ],
    height: 300,
}))

function formatPrice({ cellValue }) {
    return (!cellValue || Number.isNaN(cellValue)) ? '' : `¥${cellValue.toFixed(2)}元`
}

const productName = ref()

function filterTableList() {
    if (productName.value) {
        const result = data.value?.agreementProductVOList.filter((item: any) => {
            return item.productName.includes(productName.value)
        })
        gridOptions.value.data = cloneDeep(result) ?? []
    }
    else {
        gridOptions.value.data = cloneDeep(data.value?.agreementProductVOList) ?? []
    }
}

function showFile(file: any) {
    if (file)
        window.open(file)
}

function showDetail(row: any) {
    if (row?.productObject) {
        window.sessionStorage.setItem('PRODUCT_DETAIL', row.productObject)

        push('/operations-pages/strategic-agreement/product-preview')
    }
    else {
        openNewWindow('/product-info', {
            id: row?.productCode,
        })
    }
}

function exportInfo() {
    if (id.value) {
        mutate(String(id.value), {
            onSuccess: (res: any) => {
                const objectUrl = URL.createObjectURL(res)
                location.href = objectUrl
                URL.revokeObjectURL(objectUrl)
            },
        })
    }
}

watchEffect(() => {
    if (data) {
        gridOptions.value.data = cloneDeep(data.value?.agreementProductVOList) ?? []
    }
})
</script>

<template>
    <ElSkeleton v-if="isLoading"
                :rows="5"
    />

    <div v-else
         class="flex flex-col gap-20"
    >
        <ElCard shadow="never">
            <div class="mb-20 font-700">
                {{ data?.agreementName }}
            </div>

            <ElButton type="primary"
                      :loading="isPending"
                      @click="exportInfo"
            >
                导出明细
            </ElButton>
        </ElCard>

        <ElCard shadow="never">
            <template #header>
                <div class="card-header font-700">
                    <span>基本信息</span>
                </div>
            </template>

            <el-row :gutter="20">
                <el-col :span="6">
                    协议开始时间：{{ data?.startDate }}
                </el-col>

                <el-col :span="6">
                    协议结束时间：{{ data?.endDate }}
                </el-col>

                <el-col :span="6">
                    协议类目：{{ data?.categoryName }}
                </el-col>

                <el-col :span="6">
                    协议类型：{{ agreementTypeEunm?.[data?.agreementType] }}
                </el-col>

                <el-col :span="6">
                    甲方：{{ data?.partyA }}
                </el-col>

                <el-col :span="6">
                    乙方：{{ data?.partyB }}
                </el-col>

                <el-col :span="12">
                    协议附件：

                    <ElButton v-if="data.agreementAttachment"
                              type="primary"
                              text
                              class="!p-0"
                              @click="showFile(singleFileJsonObj(data.agreementAttachment).url)"
                    >
                        {{ singleFileJsonObj(data.agreementAttachment).name }}
                    </ElButton>
                </el-col>

                <el-col v-if="isProjectContract"
                        :span="24"
                >
                    关联协议:
                    {{ data?.relationAgreementName }}
                </el-col>
            </el-row>
        </ElCard>

        <ElCard v-if="isProjectContract"
                shadow="never"
        >
            <template #header>
                <div class="card-header font-700">
                    <span>金额信息</span>
                </div>
            </template>

            <el-row :gutter="20">
                <el-col :span="6">
                    合同金额：{{ data?.contractPrice ? `${data?.contractPrice}元` : '' }}
                </el-col>
            </el-row>
        </ElCard>

        <ElCard shadow="never">
            <template #header>
                <div class="card-header font-700">
                    <span>协议产品</span>
                </div>
            </template>

            <vxe-grid v-bind="gridOptions"
                      ref="tableRef"
                      :loading="isLoading"
            >
                <template #toolbar_buttons>
                    <div class="flex w-full justify-end">
                        <el-input v-model="productName"
                                  style="max-width: 300px;min-width:300px"
                                  placeholder="请输入产品名称"
                                  class="input-with-select"
                                  clearable
                        >
                            <template #append>
                                <ElButton :icon="Search"
                                          style="background: #da0004; color:#fff"
                                          @click="filterTableList"
                                />
                            </template>
                        </el-input>
                    </div>
                </template>

                <template #operate="{ row }">
                    <span class="text-#409EFF cursor-pointer"
                          @click="showDetail(row)"
                    >
                        查看
                    </span>
                </template>
            </vxe-grid>
        </ElCard>

        <ElCard shadow="never">
            <div class="flex justify-center">
                <ElButton @click="back">
                    返回
                </ElButton>
            </div>
        </ElCard>
    </div>
</template>

<style scoped>
.el-col {
    margin-bottom: 28px;
    font-size: 16px;
    color: #1d2129;
}
</style>
